<template>
  <el-dialog custom-class="attachment-dialog"
             :visible.sync="visible"
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             width="820px"
             :title="find.length ? `已选择${find.length}个对象` : '资源媒体库'"
             :lock-scroll="false"
             @closed="closed">
    <div class="multimedia-content"
         v-loading="upload_lock"
         :element-loading-text="upload_lock"
         @dragover.prevent="dragover"
         @dragleave.prevent="dragleave"
         @drop.prevent="drop">
      <div class="multimedia-drop"
           v-if="dropStatus === 'DROP_RELEASE'">
        把文件拖到这里，松开你的鼠标。
      </div>
      <div class="multimedia-menu"
           ref="menu">
        <el-menu :default-active="menu"
                 @select="onSelectMenu">
          <el-menu-item v-for="(item,index) in typeClass"
                        :key="index"
                        :index="item.type">{{ item.name }}</el-menu-item>
        </el-menu>
      </div>

      <div @scroll="onScroll"
           class="multimedia-list"
           ref="list"
           v-show="list.length > 0">
        <ul>
          <li class="multimedia-list-item"
              v-for="item of list"
              :title="item.name"
              :key="item.id"
              @click.self="onSelect(item, !select[item.id])"
              :class="{ select: select[item.id] }">
            <img class="multimedia-list-item__img"
                 :src="item.url">
            <span class="multimedia-list-item__name">{{ item.name }}</span>
            <i class="el-icon-circle-check multimedia-list-item__checked"></i>
            <!-- <i class="el-icon-error el-icon-circle-del" @click.self="onDel"></i> -->
          </li>
        </ul>
      </div>

      <div v-show="!list.length || loading"
           class="multimedia-empty">
        <div v-if="!loading">
          <i class="el-icon-picture"></i>
          <p>还没有内容呢，把内容拖到这里上传吧。</p>
        </div>
        <div v-else>
          <i class="el-icon-loading"></i>
          <p>加载中</p>
        </div>
      </div>
    </div>

    <div slot="footer"
         class="dialog-footer">
      <div class="left">
        <el-button @click="$refs.$input.click()"
                   :loading="upload_lock ? true : false"
                   type="primary"
                   size="mini">上传</el-button>
      </div>
      <div class="right">
        <el-button @click="closed"
                   size="mini">取 消</el-button>
        <el-button :disabled="find.length == 0"
                   type="primary"
                   @click="onSubmit"
                   size="mini">选择</el-button>
      </div>
    </div>
    <input @change="selectFile"
           multiple="multiple"
           type="file"
           v-show="false"
           ref="$input">
  </el-dialog>
</template>

<script>
import { mapGetters, mapActions, mapMutations } from 'vuex';
import { ATTACHMENT_TYPE } from './config'
import { uploadAttachments } from './api'
import { getScrollToBottomed } from '@/utils/dom'

export default {
  name: 'attachments',
  data () {
    return {
      multiple: 1,
      visible: false,
      find: [],
      upload_lock: false,
      loading: false,
      menu: 'banner',
      simditor: 0,
      typeClass: ATTACHMENT_TYPE,
      dropStatus: 'DROP_FREE',
      query: {
        page: 1,
        limit: 12,
        q: undefined,
      }
    }
  },
  computed: {
    ...mapGetters('attachments', ['list', 'total']),
    images () {
      const images = [];
      this.list.forEach((item) => {
        images[item.id] = item;
        return true;
      });
      return images;
    },
    select () {
      const s = {};
      this.find.forEach((id) => {
        s[id] = this.images.slice(0)[id];
      });
      return s;
    },
  },
  methods: {
    ...mapActions('attachments', ['fetchList']),
    ...mapMutations('attachments', ['APPEND']),
    open (menu, multiple, simditor) {
      const data = this.$options.data();
      this.multiple = multiple || data.multiple;
      this.menu = menu || data.menu;
      this.simditor = simditor || data.simditor;
      this.visible = true;
      return new Promise((resolve) => {
        this._resolve = resolve;
      });
    },
    closed () {
      this.visible = false
    },
    dragover () {
      if (this.dropStatus === 'DROP_FREE') {
        this.dropStatus = 'DROP_RELEASE';
      }
    },
    dragleave () {
      if (this.dropStatus === 'DROP_RELEASE') {
        this.dropStatus = 'DROP_FREE';
      }
    },
    drop (e) {
      if (this.dropStatus === 'DROP_RELEASE') {
        this.upload(e.dataTransfer.files);
      }
    },
    selectFile (e) {
      this.upload(e.target.files);
    },
    async upload (files) {
      if (files.length > 0) {
        this.dropStatus = 'DROP_BUSY';
        try {
          const data = await uploadAttachments(this.menu, files, this.simditor, this.progress);
          this.success(data);
          this.dropStatus = 'DROP_FREE';
        } catch (error) {
          this.fail();
          this.dropStatus = 'DROP_FREE';
        }
      } else {
        this.dropStatus = 'DROP_FREE';
      }
      this.$refs.$input.value = ''
    },
    success (data) {
      this.APPEND(data);
      this.upload_lock = false;
      this.$message.success('上传成功');
    },
    fail () {
      this.upload_lock = false;
      this.$message.error('上传出错啦');
    },
    progress (percent) {
      this.upload_lock = `上传中${Math.floor(percent)}%`;
    },
    onSubmit () {
      this.closed();
      const select = [];
      this.find.forEach((id) => {
        select.push(this.images[id]);
      });
      if (this.multiple > 1) {
        return this._resolve({
          find: this.find, select,
        });
      }
      return this._resolve({
        find: this.find[0], select: select[0],
      });
    },
    onSelect (item, selected) {
      if (selected) {
        if (this.multiple > 1) {
          if (this.find.length >= this.multiple) {
            this.$message.warning(`最多只能选择${this.multiple}张`);
          } else {
            this.find.push(item.id);
          }
        } else {
          this.find = [];
          this.find.push(item.id);
        }
      } else {
        const index = this.find.indexOf(item.id);
        if (index > -1) {
          this.find.splice(index, 1);
        }
      }
    },
    onSelectMenu (val) {
      this.menu = val;
      this.find = [];
      this.getMultimedia(true);
      this.$refs.list.scrollTo(0, 0);
    },
    getMultimedia (reload) {
      if (!this.lock || reload && !this.loading) {
        this.loading = true;
        const type = this.menu;
        let point;
        if (!reload) {
          const obj = this.list[this.list.length - 1];
          if (obj) point = obj.id;
        }
        this.fetchList({ type, point }).then(() => {
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      }
    },
    onScroll () {
      const isBottom = getScrollToBottomed(this.$refs.list, 100);
      if (isBottom && !this.loading) {
        this.getMultimedia();
      }
    }
  },
  watch: {
    visible (val) {
      if (val) {
        // 初始化
        this.find = [];
        this.getMultimedia(true);
      }
      this.visible = val;
    },
  },
}
</script>

<style lang="scss">
@import "./index.scss";
</style>